package com.example.administrator.wallet.view.fragment.mine;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.R;
import com.example.administrator.wallet.base.BaseFragment;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.TokenBean;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.activity.mine.About.AboutActivity;
import com.example.administrator.wallet.view.activity.mine.Contacts.HasContactActivity;
import com.example.administrator.wallet.view.activity.mine.ExpenditureRecordActivity.ExpenditureRecordActivity;
import com.example.administrator.wallet.view.activity.mine.Help.HelpActivity;
import com.example.administrator.wallet.view.activity.mine.IncomeRecord.IncomeRecordActivity;
import com.example.administrator.wallet.view.activity.mine.Msg.MsgActivity;
import com.example.administrator.wallet.view.activity.mine.Personal.PersonalCentreActivity;
import com.example.administrator.wallet.view.activity.mine.Setting.SettingActivity;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.Bind;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.example.administrator.wallet.R.id.smart;

/**
 */
public class MineFragment extends BaseFragment{

    @Bind(R.id.ll_help_centre)
    LinearLayout mHelp_center;
    @Bind(R.id.ll_about_us)
    LinearLayout mAbout_us;
    @Bind(R.id.ll_personal_centre)
    LinearLayout mPersonal_centre;
    @Bind(R.id.ll_contacts)
    LinearLayout mContacts;
    @Bind(R.id.ll_transaction_records)
    LinearLayout mTransaction_records;
    @Bind(R.id.ll_transfer_records)
    LinearLayout mTransfer_records;

    @Bind(R.id.ib_setting)
    ImageButton mIb_setting;
    @Bind(R.id.rl_msg)
    RelativeLayout mRl_msg;
    @Bind(R.id.ib_head)
    CircleImageView mIv_head;
    @Bind(R.id.tv_name)
    TextView mTv_name;
    @Bind(R.id.tv_btc_conversion)
    TextView mTv_btc_conversion;

    @Bind(R.id.refresh)
    ClassicsHeader mine_refresh;
    @Bind(smart)
    SmartRefreshLayout mine_smart;
    private TokenBean tokenBean;
    private String token = "";
    private static Bitmap bitmap;



    @Override
    public void init() {

        initData();
        mine_smart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (refreshlayout.isRefreshing()) {
                    initData();
                }
            }
        });
        mIb_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), SettingActivity.class));
            }
        });

        mRl_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MsgActivity.class));
            }
        });

        mTransaction_records.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), IncomeRecordActivity.class));

            }
        });

        mTransfer_records.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ExpenditureRecordActivity.class));
            }
        });

        mPersonal_centre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), PersonalCentreActivity.class));
            }
        });

        mContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(getActivity(), HasContactActivity.class));
            }
        });

        mHelp_center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), HelpActivity.class));
            }
        });

        mAbout_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), AboutActivity.class));
            }
        });



    }

    @Override
    public int getLayoutResource() {
        return R.layout.fragment_mine;
    }
    public void initData() {
        final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
        final Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        mIv_head.setImageBitmap(bitmap);
                        break;
                }
            }
        };
        token = SharedPrefsUtil.getValue(getActivity(),"wallet", "token","");

        reqequestManager.httpPost(Api.BaseUrl + Api.User_Information, Api.getUserInformation(token,""), new IRequestCallback(){

            @Override
            public void onSuccess(String Response) {
                Gson gson = new Gson();
                tokenBean = gson.fromJson(Response, TokenBean.class);
                mine_smart.finishRefresh();
                String name = tokenBean.getData().getNickname();
                final String head = tokenBean.getData().getHead_portrait();
                Log.e("tag!!111",tokenBean.getData().getHead_portrait());


                String rate = tokenBean.getData().getRate();
//                mIv_head.setImageDrawable(Drawable.createFromPath(head));
                mTv_name.setText(name);
                mTv_btc_conversion.setText(rate);
                // 显示
                new Thread() {
                    public void run() {
                        bitmap = getHttpBitmap(head);
                        Message msg = handler.obtainMessage();
                        msg.obj = bitmap;
                        SharedPrefsUtil.putValue(getActivity(), "wallet", "head_img", tokenBean.getData().getHead_portrait());
                        SharedPrefsUtil.putValue(getActivity(), "wallet", "name", tokenBean.getData().getNickname());
                        msg.what = 1;
                        handler.sendMessage(msg);
                    };
                }.start();
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(getActivity(),R.string.getphone,Toast.LENGTH_LONG).show();
            }
        });
    }
    /**
     * 获取网落图片资源
     *
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url) {
        URL myFileURL;
        Bitmap bitmap = null;
        try {
            myFileURL = new URL(url);
            // 获得连接
            HttpURLConnection conn = (HttpURLConnection) myFileURL
                    .openConnection();
            // 设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            // 连接设置获得数据流
            conn.setDoInput(true);
            // 不使用缓存
            conn.setUseCaches(false);
            // 这句可有可无，没有影响
            conn.connect();
            // 得到数据流
            InputStream is = conn.getInputStream();
            // 解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            // 关闭数据流
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
